import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import FileRepository from "@ckeditor/ckeditor5-upload/src/filerepository";

/**
 * @module upload/adapters/thinkuploadimageadapter
 */
export default class ThinkUploadImageAdapter extends Plugin {
    /**
     * @inheritDoc
     */
    static get requires() {
        return [FileRepository];
    }

    /**
     * @inheritDoc
     */
    static get pluginName() {
        return 'ThinkUploadImageAdapter';
    }

    /**
     * @inheritDoc
     */
    init() {
        this.editor.plugins.get(FileRepository).createUploadAdapter = loader => new Adapter(loader);
    }
}

class Adapter {
    /**
     * Creates a new adapter instance.
     *
     * @param {module:upload/filerepository~FileLoader} loader
     */
    constructor(loader) {
        this.loader = loader;
    }

    /**
     * Starts the upload process.
     *
     * @see module:upload/filerepository~UploadAdapter#upload
     * @returns {Promise}
     */
    upload() {
        return new Promise((resolve, reject) => {
            if (window.AdminUploadAdapter) {
                this.loader.file.then(function (file) {
                    (new window.AdminUploadAdapter()).upload([file], function (url) {
                        resolve({urls: {default: url}});
                    });
                });
            } else {
                const reader = this.reader = new window.FileReader();
                reader.addEventListener('load', () => {
                    resolve({default: reader.result});
                });
                reader.addEventListener('error', err => {
                    reject(err);
                });
                reader.addEventListener('abort', () => {
                    reject();
                });
                this.loader.file.then(file => {
                    reader.readAsDataURL(file);
                });
            }
        });
    }

    /**
     * Aborts the upload process.
     *
     * @see module:upload/filerepository~UploadAdapter#abort
     * @returns {Promise}
     */
    abort() {
        this.reader.abort();
    }
}